package com.daoshun.common;

import java.io.IOException;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

public class ImageUtil {

	// 压缩高度
	private int compressHeight = 250;
	// 压缩宽度
	private int compressWidth = 250;
	// 压缩质量
	private float compressQuaity = 0.8f;

	public int getCompressHeight() {
		return compressHeight;
	}

	public void setCompressHeight(int compressHeight) {
		this.compressHeight = compressHeight;
	}

	public int getCompressWidth() {
		return compressWidth;
	}

	public void setCompressWidth(int compressWidth) {
		this.compressWidth = compressWidth;
	}

	public float getCompressQuaity() {
		return compressQuaity;
	}

	public void setCompressQuaity(float compressQuaity) {
		this.compressQuaity = compressQuaity;
	}

	/**
	 * @Description 图片压缩，等比情况下以宽度度为准，非等比情况下要同时设置宽高 覆盖源文件
	 * 
	 * @param originFile
	 *            源文件路径
	 * @param isProportional
	 *            是否等比
	 */
	public void compressImage(String originFile, boolean isProportional) {
		try {
			if (isProportional) {
				Thumbnails.of(originFile).width(compressWidth).keepAspectRatio(true).outputQuality(compressQuaity)
						.toFile(originFile);
			} else {
				// 按指定大小缩放
				Thumbnails.of(originFile).size(compressWidth, compressHeight).keepAspectRatio(false)
						.outputQuality(compressQuaity).toFile(originFile);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void compressImage(String originFile, boolean isProportional, String newFilePath) {
		try {
			if (isProportional) {
				Thumbnails.of(originFile).width(compressWidth).keepAspectRatio(true).outputQuality(compressQuaity)
						.toFile(newFilePath);
			} else {
				// 按指定大小缩放
				Thumbnails.of(originFile).size(compressWidth, compressHeight).keepAspectRatio(false)
						.outputQuality(compressQuaity).toFile(newFilePath);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description 生成缩略图，居中裁剪，以短边为准
	 * @param originFile
	 *            原图片文件
	 * @param newFile
	 *            缩略图文件
	 */
	public void imageThumb(String originFile, String newFile) {
		// String extension =
		// newFile.substring(newFile.lastIndexOf(".")).toLowerCase();
		try {
			if (compressHeight >= compressWidth) {
				Thumbnails.of(originFile).width(compressWidth).keepAspectRatio(true).outputQuality(compressQuaity)
						.toFile(newFile);
				Thumbnails.of(newFile).size(compressWidth, compressWidth)
						.sourceRegion(Positions.CENTER, compressWidth, compressWidth).toFile(newFile);
			} else {
				Thumbnails.of(originFile).height(compressHeight).keepAspectRatio(true).outputQuality(compressQuaity)
						.toFile(newFile);
				Thumbnails.of(newFile).size(compressHeight, compressHeight)
						.sourceRegion(Positions.CENTER, compressHeight, compressHeight).toFile(newFile);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
